package com.sq.imp.MyMenuManagers;

import com.sq.abstractClass.Text;
import com.sq.imp.Calculator.CalculatorWindow;

import javax.swing.*;
import java.awt.*;

public class CalculatorManager {
    Text textArea;
    JFrame frame;
    public JMenu  calculator = new JMenu("计算器");
    public CalculatorManager(Text textArea, JFrame frame) {
        this.textArea = textArea;
        this.frame = frame;
        JMenuItem calculatorItem = new JMenuItem("选择文本计算器");
        calculator.add(calculatorItem);

        calculatorItem.addActionListener(e -> openCalculator());

    }

    // 打开计算器的方法
    private void openCalculator() {
        String selectedText = textArea.getSelectedText();
        if (selectedText == null || selectedText.isEmpty()) {
//            JOptionPane.showMessageDialog(frame, "请先选中一段文本", "提示", JOptionPane.INFORMATION_MESSAGE);
        } else if (!isMathExpression(selectedText)) {
            JOptionPane.showMessageDialog(frame, "选中的文本不是有效的数学表达式", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
        new CalculatorWindow(selectedText, mouseLocation).setVisible(true);
    }

    private boolean isMathExpression(String text) {
        return text.matches("[\\d+\\-*/%^().!\\s]+");
    }
}
